import React, { useRef, useEffect, useState } from 'react';
import { Rnd } from 'react-rnd';
import { FullscreenOutlined, ShrinkOutlined } from '@ant-design/icons';

const ASPECT_RATIO = 4 / 3; // 摄像头常见比例

export default function CameraBox() {
  const videoRef = useRef(null);
  const [full, setFull] = useState(false);
  const [size, setSize] = useState({ width: 320, height: 240 });
  const [position, setPosition] = useState({ x: 16, y: 16 });

  useEffect(() => {
    async function getCamera() {
      try {
        const stream = await navigator.mediaDevices.getUserMedia({ video: true });
        if (videoRef.current) {
          videoRef.current.srcObject = stream;
        }
      } catch (err) {
        // 可处理无权限等情况
      }
    }
    getCamera();
  }, []);

  // 铺满左半屏
  const handleFull = () => {
    setFull(!full);
    if (!full) {
      setSize({ width: window.innerWidth / 2, height: (window.innerWidth / 2) / ASPECT_RATIO });
      setPosition({ x: 0, y: 0 });
    } else {
      setSize({ width: 320, height: 240 });
      setPosition({ x: 16, y: 16 });
    }
  };

  return (
    <Rnd
      size={size}
      position={position}
      minWidth={160}
      minHeight={120}
      maxWidth={full ? window.innerWidth / 2 : 600}
      maxHeight={full ? window.innerHeight : 450}
      lockAspectRatio={ASPECT_RATIO}
      disableDragging={full}
      enableResizing={!full}
      onDragStop={(e, d) => setPosition({ x: d.x, y: d.y })}
      onResizeStop={(e, direction, ref, delta, pos) => {
        const width = parseInt(ref.style.width, 10);
        setSize({ width, height: width / ASPECT_RATIO });
        setPosition(pos);
      }}
      style={{
        zIndex: 1000,
        border: '2px solid #1890ff',
        background: '#000',
        borderRadius: 8,
        overflow: 'hidden',
        boxShadow: '0 2px 8px rgba(0,0,0,0.15)'
      }}
      bounds="window"
    >
      <div style={{ width: '100%', height: '100%', position: 'relative' }}>
        <video
          ref={videoRef}
          autoPlay
          muted
          playsInline
          style={{ width: '100%', height: '100%', objectFit: 'cover', borderRadius: 8 }}
        />
        <button
          onClick={handleFull}
          style={{
            position: 'absolute',
            top: 8,
            right: 8,
            background: 'rgba(24,144,255,0.8)',
            border: 'none',
            borderRadius: 4,
            color: '#fff',
            padding: 4,
            cursor: 'pointer'
          }}
        >
          {full ? <ShrinkOutlined /> : <FullscreenOutlined />}
        </button>
      </div>
    </Rnd>
  );
}
